package gov.pbc.nn.core.bdf.interceptor;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.dorado.common.proxy.PatternMethodInterceptor;
import com.bstek.dorado.core.Configure;
import com.bstek.dorado.view.resolver.ClientRunnableException;

/**
 * Session超时拦截
 * 
 * @author louis
 * 
 */
public class TimeoutInvokeInterceptor extends PatternMethodInterceptor {

	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		HttpServletRequest request = ContextHolder.getRequest();
		String origin = request.getHeader("Origin");
		if (StringUtils.isEmpty(origin)) {
			String uri = request.getRequestURI();
			String url = request.getRequestURL().toString();
			origin = StringUtils.substringBefore(url, uri);
		}
		String referer = request.getHeader("Referer");
		String contextPath = request.getContextPath();
		origin += contextPath;
		String path = StringUtils.substringAfter(referer, origin);

		if (!this.match(path)) {
			if (StringUtils.isBlank(ContextHolder.getLoginUserName())) {
				String loginUrl = Configure.getString("bdf2.formLoginUrl");
				if (StringUtils.equalsIgnoreCase(
						Configure.getString("bdf2.authenticationType"), "cas")) {
					loginUrl = Configure
							.getString("bdf2.loginSuccessDefaultTargetUrl");
				}
				StringBuffer sb = new StringBuffer();
				sb.append("var d = dorado.MessageBox.getDialog();");
				sb.append("d.set('closeable', false);");
				sb.append("dorado.MessageBox.show({icon : 'WARNING',buttons:['ok'],message :'由于您长时间未操作，因此您需要重新登录！',callback:function(){window.top.location.href='"
						+ contextPath + loginUrl + "';}})");
				throw new ClientRunnableException(sb.toString());
			}
		}
		return invocation.proceed();
	}

	private boolean match(String path) {
		String register = Configure
				.getString("bdf2.userRegisterMainWizardPath");
		String formLogin = Configure.getString("bdf2.formLoginUrl");
		String[] excludes = new String[] { register, formLogin };
		if (ArrayUtils.contains(excludes, path)) {
			return true;
		} else {
			return StringUtils.startsWithAny(path, new String[] { register,
					formLogin });
		}
	}

}
